#include "volumeplan.h"
#include "scheduler.h"
#include "common.h"
#include "Player.h"
#include "subwindowsetvolumefunctor.h"

#include <QTime>
#include <QDebug>
#include <QFile>
#include <QFileInfo>

VolumePlan::VolumePlan(const QString &volumePlanFilePath):
		m_VolumePlanFilePath(volumePlanFilePath)
{
	QFile volumePlanFile(m_VolumePlanFilePath);
	if(!m_VolumePlan.setContent(&volumePlanFile))
	{
		QString errorMsg = QString("Parse volume plan file %1 error").arg(m_VolumePlanFilePath);
		qDebug()<<errorMsg;
	}
}

void VolumePlan::doCommand()
{

	QFileInfo fileInfo(m_VolumePlanFilePath);
	bool isOk;
	int windowNo = fileInfo.baseName().toInt(&isOk);
	if(!isOk)
	{
		QString errorMsg = QString("Get window no from file %1 error").arg(m_VolumePlanFilePath);
		qDebug()<<errorMsg;
		return;
	}

	qDebug()<<m_VolumePlan.toByteArray();
	QDomElement rootElement = m_VolumePlan.firstChildElement();

	QDomElement element = rootElement.firstChildElement();

	QTime currentTime = QTime::currentTime();
	g_VolumeScheduler->clearScheduler(windowNo);
	g_VolumeScheduler->start();

	while(element != QDomElement())
	{
		QTime startTime = QTime::fromString(element.attribute("StartTime"), "hh:mm");
		QTime endTime = QTime::fromString(element.attribute("EndTime"), "hh:mm");

		int percentage = element.attribute("Percentage").toInt();

		SubWindowSetVolumeFunctor setVolume(windowNo, percentage / 100.0);

		if(startTime <= currentTime && currentTime <= endTime)
		{
			setVolume();
		}
		else
		{
			g_VolumeScheduler->addEventToSchedule(windowNo, startTime, endTime, setVolume);
		}

		element = element.nextSiblingElement();
	}
}
